package com.qdlc.p2p.dal.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.DataUtils;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dao.AccountCashDao;
import com.qdlc.p2p.dal.dto.AccountCash;
import com.qdlc.p2p.dal.model.AccountCashModel;
import com.qdlc.p2p.dal.mybatis.model.mapper.AccountCashMapper;
import com.qdlc.p2p.dal.mybatis.pager.PageProxyBuilder;
import com.qdlc.p2p.dal.mybatis.pager.core.PageParameter;

@Repository("accountCashDao")
public class AccountCashDaoImpl implements AccountCashDao {

    @Resource
    AccountCashMapper accountCashMapper;

    @Override
    public void insert(AccountCash accountCash) {
        accountCashMapper.insert(accountCash);
    }

    @Override
    public void update(AccountCash cash) {
        accountCashMapper.update(cash);
    }

    /**
     * 根据Id查找
     *
     * @param id
     * @return
     */
    @Override
    public AccountCash findById(long id) {
        AccountCash accountCash = accountCashMapper.findById(id);
        return accountCash;
    }

    @Override
    public List<AccountCash> findByUserId(long userId, int status) {
        return accountCashMapper.findByUserId(userId, status);
    }

    public List<AccountCash> findByLimitAddTime(int status, Date addTime) {
        return accountCashMapper.findByLimitAddTime(status, addTime);
    }

    @Override
    public AccountCash getCashMessage(long userId) {
        return accountCashMapper.countAountTotalsByUserId(userId);
    }

    @Override
    public void updateStatus(long id, int status, int preStatus) {
        accountCashMapper.updateStatus(id, status, preStatus);
    }

    @Override
    public void verifyCash(long id, int status, int preStatus, String verityRemark, String verifyUserName) {
        accountCashMapper.verifyCash(id, status, preStatus, verityRemark, verifyUserName);
    }

    @Override
    public int count(int status) {
        return accountCashMapper.countByStatus(status);
    }

    @Override
    public double allCashMoney() {
        Double allMoney = accountCashMapper.allCashMomeny();
        return allMoney == null ? 0.0D : allMoney;
    }

    @Override
    public double getCashFeeByDate(String date) {
        Double dateFee = accountCashMapper.getCashFeeByDate(date);
        return dateFee == null ? 0.0D : dateFee;
    }

    @Override
    public int getApplyingCount(long userId) {
        Integer count = accountCashMapper.getApplyingCount(userId);
        return count == null ? 0 : count;
    }

    @Override
    public int getSingleDaytime(long userId) {
        Integer times = accountCashMapper.getSingleDaytime(userId);
        return times == null ? 0 : times;
    }

    @Override
    public double getSingleDayAmount(long userId) {
        Double totalAmount = accountCashMapper.getSingleDayAmount(userId);
        return totalAmount == null ? 0.0D : totalAmount;
    }

    @Override
    public int getMonthFreeFeeTime(long userId) {
        Integer times = accountCashMapper.getMonthFreeFeeTime(userId);
        return times == null ? 0 : times;
    }

    @Override
    public AccountCash getAccountCashByOrderNo(String orderNo) {
        AccountCash cash = accountCashMapper.getAccountCashByOrderNo(orderNo);
        return cash;
    }

    @Override
    public PageDataList<AccountCashModel> list(long userId, int startPage, AccountCashModel model) {
    	
    	//使用分页代理器
		PageProxyBuilder<AccountCashMapper> proxy = PageProxyBuilder.newBuilder(AccountCashMapper.class);
		proxy.setPageParameter(model.getPage(), model.getRows());
		Date nowDate = DateUtil.getNow();
		model.setStartDateAndEndDate();
		Date rollDay = null;
		if (model.getTime() == 7) {
			rollDay=DateUtil.rollDay(nowDate, -7);
			model.setStartDate(rollDay);
			model.setEndDate(nowDate);
		}
		else if ((model.getTime() > 0) && (model.getTime() < 4)) {
			rollDay = DateUtil.rollMon(nowDate, -model.getTime());
			model.setStartDate(rollDay);
			model.setEndDate(nowDate);
       	}
		model.setUserId(userId);
		List<AccountCashModel> accountCashModelList = proxy.createProxy().findByModel(model);
		//获取分页参数
		PageParameter pageParameter = proxy.getPageParameter();
		PageDataList<AccountCashModel> pageDataList = new PageDataList<AccountCashModel>(pageParameter.convert2Page(), accountCashModelList);
		return pageDataList;
    }

    @Override
    public PageDataList<AccountCashModel> accountCashList(AccountCashModel model) {
        PageProxyBuilder<AccountCashMapper> proxy = PageProxyBuilder.newBuilder(AccountCashMapper.class);
        proxy.setPageParameter(model.getPage(), model.getRows());
        List<AccountCashModel> modelList;
        if (!StringUtil.isBlank(model.getSearchName())) {// 模糊条件查询
            modelList = proxy.createProxy().findByUserName(model.getSearchName().trim());
        } else {// 精确条件查询
            modelList = proxy.createProxy().findByModel(model);
        }
        PageParameter pageParameter = proxy.getPageParameter();
        PageDataList<AccountCashModel> pageDateList = new PageDataList<AccountCashModel>(pageParameter.convert2Page(), modelList);
        return pageDateList;
    }

    @Override
    public double getWithdrawCashManageFeeByUserId(long userId) {
        // 提现到帐一般情况是1天,为防止提现到账延迟 故查找了5天内还处理提现中的手续费用
        Map<String, Object> resultMap = accountCashMapper.getWithdrawCashManageFeeByUserId(userId, DateUtil.dateStr2(DateUtil.rollDay(DateUtil.getNow(), -5)));
        int feeCount = DataUtils.toInt(resultMap.get("feeCount"));
        double fee = DataUtils.toDouble(resultMap.get("fee"));

        // 提现频率率 = 提现中回数 * 提现费率
        double cashRate = BigDecimalUtil.mul(feeCount, SystemConfigHelper.getDoubleValue(SystemConfigHelper.Nid.CASH_SERV_FEE));
        // 提现现金 - 提现频率率
        double result = BigDecimalUtil.sub(fee, cashRate);
        return result < 0 ? 0 : result;
    }

    @Override
    public double getWithdrawAmountByDate(String date) {
        String dateFormat = "%Y-%m-%d";
        if (date.length() == 7) {
            dateFormat = "%Y-%m";
        }
        Double amount = accountCashMapper.getWithdrawAmountByDate(dateFormat,date);
        return amount == null ? 0.0D : amount;
    }
}
